package net.lab1024.sa.admin.module.business.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.business.place.manager.PlaceCacheManager;
import net.lab1024.sa.admin.module.business.shop.dao.ShopDao;
import net.lab1024.sa.admin.module.business.shop.dao.ShopRangeDao;
import net.lab1024.sa.admin.module.business.shop.domain.Enity.ShopEntity;
import net.lab1024.sa.admin.module.business.shop.domain.Enity.ShopRangeEntity;
import net.lab1024.sa.admin.module.business.shop.domain.ShopRangeVO;
import net.lab1024.sa.admin.module.business.shop.domain.ShopTree;
import net.lab1024.sa.admin.module.business.shop.domain.ShopVO;
import net.lab1024.sa.admin.module.business.shop.domain.form.ShopQueryForm;
import net.lab1024.sa.admin.module.business.shop.domain.form.ShopAddForm;
import net.lab1024.sa.admin.module.business.shop.domain.form.ShopUpdateForm;
import net.lab1024.sa.admin.module.business.sp.dao.SpDao;
import net.lab1024.sa.base.common.code.UserErrorCode;
import net.lab1024.sa.base.common.domain.PageResult;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.util.SmartBeanUtil;
import net.lab1024.sa.base.common.util.SmartPageUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ShopService {
    @Resource
    private ShopDao shopDao;
    @Resource
    private ShopRangeDao shopRangeDao;
    @Resource
    private PlaceCacheManager placeCacheManager;
    @Resource
    private SpDao spDao;
    public ResponseDTO<PageResult<ShopVO>> queryShopPage(ShopQueryForm queryForm) {
        Page<?> page = SmartPageUtil.convert2PageQuery(queryForm);
        List<ShopVO> entityList = shopDao.queryByPage(page, queryForm);
        PageResult<ShopVO> pageResult = SmartPageUtil.convert2PageResult(page, entityList, ShopVO.class);
        return ResponseDTO.ok(pageResult);
    }

    public ResponseDTO<List<ShopTree>> queryShopTree() {
        List<ShopEntity> entityList = shopDao.selectList( new QueryWrapper<ShopEntity>().eq("is_del", 0));
        List<ShopTree> treeList = entityList.stream().map(e -> {
            ShopTree tree = new ShopTree();
            tree.setId(e.getShopId());
            tree.setName(e.getShopName());
            return tree;
        }).collect(Collectors.toList());
        treeList.forEach(e -> {
            e.setChildrens(spDao.selectByShopId(e.getId()));
        });
        return ResponseDTO.ok(treeList);

    }
    public ResponseDTO<PageResult<ShopVO>> queryShop(ShopQueryForm employeeQueryForm) {
//        employeeQueryForm.setDeletedFlag(false);
        Page pageParam = SmartPageUtil.convert2PageQuery(employeeQueryForm);
        List<ShopVO> employeeList = shopDao.queryByPage(pageParam, employeeQueryForm);
        if (CollectionUtils.isEmpty(employeeList)) {
            PageResult<ShopVO> pageResult = SmartPageUtil.convert2PageResult(pageParam, employeeList);
            return ResponseDTO.ok(pageResult);
        }

        List<Long> employeeIdList = employeeList.stream().map(ShopVO::getShopId).collect(Collectors.toList());
        // 查询类型角色
        List<ShopRangeVO> roleEmployeeEntityList = shopRangeDao.selectTypeListByShopId(employeeIdList);
        Map<Long, List<Long>> employeeRoleIdListMap = roleEmployeeEntityList.stream().collect(Collectors.groupingBy(ShopRangeVO::getShopId, Collectors.mapping(ShopRangeVO::getTypeId, Collectors.toList())));
        Map<Long, List<String>> employeeRoleNameListMap = roleEmployeeEntityList.stream()
                .collect(Collectors.groupingBy(ShopRangeVO::getShopId, Collectors.mapping(ShopRangeVO::getTypeName, Collectors.toList())));

        employeeList.forEach(e -> {
            e.setShopRange(employeeRoleIdListMap.getOrDefault(e.getShopId(), Lists.newArrayList()));
            e.setShopRangeName(employeeRoleNameListMap.getOrDefault(e.getShopId(), Lists.newArrayList()));
            e.setPlaceName(placeCacheManager.queryPlaceTreeByName(e.getPlaceId()));
        });
        PageResult<ShopVO> pageResult = SmartPageUtil.convert2PageResult(pageParam, employeeList);
        return ResponseDTO.ok(pageResult);
    }
    public ResponseDTO<String> add(ShopAddForm shopAddDTO) {
        List<ShopEntity> alreadyEntity = shopDao.selectByName(String.valueOf(shopAddDTO.getShopName()));
        ShopEntity entity = SmartBeanUtil.copy(shopAddDTO, ShopEntity.class);
        if (alreadyEntity.contains(entity)) {
            return ResponseDTO.error(UserErrorCode.ALREADY_EXIST);
        }

        entity.setCreateTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        entity.setCreateBy("syf");
        entity.setUpdateBy("syf");
        shopDao.insert(entity);
        ShopEntity shopEntity = shopDao.selectByName(String.valueOf(shopAddDTO.getShopName())).get(0);
        Long configId = shopEntity.getShopId();
        int i;
        shopRangeDao.deleteByShopId(shopEntity.getShopId());
        for (i=0; i<shopAddDTO.getShopRange().size(); i++){
            ShopRangeEntity a = new ShopRangeEntity(configId,shopAddDTO.getShopRange().get(i));
            shopRangeDao.insert(a);
        }
        return ResponseDTO.ok();
    }
    public ResponseDTO<String> updateShop(ShopUpdateForm updateDTO) {
        Long configId = updateDTO.getShopId();
        ShopEntity entity = shopDao.selectById(configId);
        if (null == entity) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        entity = SmartBeanUtil.copy(updateDTO, ShopEntity.class);
        List<ShopEntity> alreadyEntity = shopDao.selectByName(updateDTO.getShopName());
        if (null != alreadyEntity && alreadyEntity.contains(entity)) {
            return ResponseDTO.error(UserErrorCode.ALREADY_EXIST, "商户已存在");
        }

        // 更新数据
//        entity = SmartBeanUtil.copy(updateDTO, ShopEntity.class);
        entity.setUpdateTime(new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
        int i;
        shopRangeDao.deleteByShopId(configId);
        for (i=0; i<updateDTO.getShopRange().size(); i++){
        ShopRangeEntity a = new ShopRangeEntity(configId,updateDTO.getShopRange().get(i));
        shopRangeDao.insert(a);
        }
        shopDao.updateById(entity);
        return ResponseDTO.ok();
    }
    public ResponseDTO<String> deleteShop(ShopUpdateForm updateDTO) {
        Long configId = updateDTO.getShopId();
        ShopEntity entity = shopDao.selectById(configId);
        if (null == entity) {
            return ResponseDTO.error(UserErrorCode.DATA_NOT_EXIST);
        }
        // 更新数据
        entity = SmartBeanUtil.copy(updateDTO, ShopEntity.class);
        entity.setDel(true);
        shopDao.updateById(entity);
        return ResponseDTO.ok();
    }

}
